package com.mucd.chat.handle;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author Apple
 * @Description: 握手拦截器
 * @Version: 1.0
 */
public class MyWebSocketInterceptor implements HandshakeInterceptor {


    /**
     * // 返回 false 将取消握手，即拒绝连接
     * // 返回 true 表示继续握手
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 在这里添加你的拦截逻辑
// 获取 URI
        URI uri = request.getURI();

        // 获取查询字符串
        String query = uri.getQuery();

        // 解析查询字符串
        List<NameValuePair> params = URLEncodedUtils.parse(query, StandardCharsets.UTF_8);
        for (NameValuePair param : params) {
            if ("Authorization".equals(param.getName())) {
                String token = param.getValue();
                // 在这里你可以使用 token
                return verifyToken(token);
            }
        }

        return false;
    }

    private boolean verifyToken(String token) {
        TokenService tokenService = SpringUtils.getBean(TokenService.class);
        return tokenService.verifyToken(token);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}